package com.pig4cloud.pig.module.service.base.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.MathUtil;
import com.pig4cloud.pig.common.core.wx.WxMessage;
import com.pig4cloud.pig.module.api.entity.Parameter;
import com.pig4cloud.pig.module.api.entity.SysUserWxAdmin;
import com.pig4cloud.pig.module.api.entity.charger.Charger;
import com.pig4cloud.pig.module.api.entity.charger.ChargerOrder;
import com.pig4cloud.pig.module.api.entity.electric.ElectricOrder;
import com.pig4cloud.pig.module.api.entity.estate.EstateUser;
import com.pig4cloud.pig.module.api.entity.estate.RepairRecord;
import com.pig4cloud.pig.module.api.entity.estate.Worker;
import com.pig4cloud.pig.module.api.entity.mer.MerEggSettlement;
import com.pig4cloud.pig.module.api.entity.product.ProductOrderWarmHeart;
import com.pig4cloud.pig.module.api.entity.promoter.Promoter;
import com.pig4cloud.pig.module.api.entity.promoter.PromoterSettlement;
import com.pig4cloud.pig.module.api.entity.property.PropertyFeeOrder;
import com.pig4cloud.pig.module.api.entity.wx.*;
import com.pig4cloud.pig.module.mapper.SysUserWxAdminMapper;
import com.pig4cloud.pig.module.mapper.promoter.PromoterMapper;
import com.pig4cloud.pig.module.mapper.property.PropertyFeeOrderMapper;
import com.pig4cloud.pig.module.mapper.wx.UserMpMapper;
import com.pig4cloud.pig.module.mapper.wx.WxTemplateMapper;
import com.pig4cloud.pig.module.mapper.wx.WxUserMapper;
import com.pig4cloud.pig.module.service.base.IParameterService;
import com.pig4cloud.pig.module.service.charger.IChargerService;
import com.pig4cloud.pig.module.service.estate.IEstateUserService;
import com.pig4cloud.pig.module.service.estate.IWorkerService;
import com.pig4cloud.pig.module.service.wx.IWxTemplateService;
import com.vdurmont.emoji.EmojiParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信公众号的模板消息列Service业务层处理
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Service
public class WxTemplateServiceImpl extends ServiceImpl<WxTemplateMapper, WxTemplate> implements IWxTemplateService {

	@Resource
	private PropertyFeeOrderMapper feeOrderMapper;
	@Resource
	private UserMpMapper userMpMapper;
	@Resource
	private WxTemplateMapper wxTemplateMapper;
	@Resource
	protected RedisTemplate<String, Object> redisTemplate;
	@Resource
	private WxUserMapper wxUserMapper;
	@Resource
	private SysUserWxAdminMapper sysUserWxAdminMapper;
	@Resource
	private IEstateUserService estateUserService;
	@Resource
	private IWorkerService workerService;
	@Resource
	private IParameterService parameterService;
	@Resource
	private IChargerService chargerService;
	@Resource
	private PromoterMapper promoterMapper;

	@Value("${web.appid}")
	private String appid;//小程序appid
	@Value("${web.secret}")
	private String secret;//小程序appid
	@Value("${web.appidMp}")
	private String appidMp;//公众号appid
	@Value("${web.secretMp}")
	private String secretMp;//公众号secret

	@Override
	@Transactional
	public String getAccessToken(int type) {
		String access_token = "";
		try{
			Parameter parameter = parameterService.findById(1);
			if(type == 0){//公众号
				access_token = parameter.getAccessTokenMp();
				if(new Date().getTime() > parameter.getAcMpLastTime().getTime()){
					access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
					parameter.setAccessTokenMp(access_token);
					//记录2小时之后的时间s
					parameter.setAcMpLastTime(DateUtils.getAfterSecondsByOld(new Date(),7200));
					parameterService.updateById(parameter);
				}
			}else{//小程序
				access_token = parameter.getAccessToken();
				if(new Date().getTime() > parameter.getAcLastTime().getTime()) {
					access_token = WxMessage.getACCESSTOKEN(appid, secret);
					parameter.setAccessToken(access_token);
					parameter.setAcLastTime(DateUtils.getAfterSecondsByOld(new Date(),7200));
					parameterService.updateById(parameter);
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return access_token;
	}

	/**
	 * 订单支付成功 公众号推送消息
	 * @param user
	 * @param feeOrder
	 * @return
	 */
	@Override
	public int sendWxMsgByPropertyFee(WxUser user, PropertyFeeOrder feeOrder) {
		try{
//			String accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);

//			String accessToken = redisTemplate.opsForValue().get("access_token_mp") !=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//			if(StrUtil.isEmpty(accessToken)){
//				accessToken = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//				redisTemplate.opsForValue().set("access_token_mp",accessToken,3600L, TimeUnit.SECONDS);
//			}
			String access_token = getAccessToken(0);//WxMessage.getACCESSTOKEN(appidMp,secretMp);

			QueryWrapper<UserMp> qw = new QueryWrapper<>();
			qw.eq("union_id",user.getUnionId());
			qw.last("limit 1");
			UserMp userMp = userMpMapper.selectOne(qw);
			if(userMp!=null){
				WxMsgTemplate template = getTemplateToUser(userMp,feeOrder,19);
				String param = JSONUtil.parseObj(template).toString();
				System.out.println("公众号推送消息 - 用户端请求信息:" + param);
				JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
				System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
				return 1;
			}
			return 0;
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  发送推送消息到 商家管理员微信上
	 * @param userMp
	 * @param feeOrder
	 * @param template_type   10  物业费用通知
	 * @return
	 */
	private WxMsgTemplate getTemplateToUser(UserMp userMp, PropertyFeeOrder feeOrder, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniProgram = new HashMap<>();
			miniProgram.put("appid",appid);
			miniProgram.put("pagepath","pagesProperty/pages/propertyList/index?state=0");
			template.setMiniprogram(miniProgram);

			Map<String, MsgTempData> m = new HashMap<>();

//			物业费：10元
//			代收水费：10元
//			代收电费：10元
//			垃圾处理费：10元
//			交费时间段：2022-3月~2022-3月
//			感谢您的关注与使用，具体详情，请点击查看进行操作。
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的业主您好，我们根据您的申请，已生成物业•费用清单");
			m.put("first",first);

			//物业费
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(feeOrder.getWyfFee()+"元");
			m.put("keyword1",keyword1);

			//代收水费
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(feeOrder.getElectricFee()+ "元");
			m.put("keyword2",keyword2);

			//代收电费
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(feeOrder.getWaterFee()+ "元");
			m.put("keyword3",keyword3);

			//垃圾处理费
			MsgTempData keyword4 = new MsgTempData();
			keyword4.setColor(wxTemplate.getFontColor());
			keyword4.setValue(feeOrder.getTrashFee()+ "元");
			m.put("keyword4",keyword4);

			//交费时间段
			MsgTempData keyword5 = new MsgTempData();
			keyword5.setColor(wxTemplate.getFontColor());
			String date =  DateUtils.getYearMonthTime(feeOrder.getBeginTime())
				+ "~" + DateUtils.getYearMonthTime(feeOrder.getEndTime());
			keyword5.setValue(date);
			m.put("keyword5",keyword5);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
//			feeOrder.getEstateName() + " " + feeOrder.getRoomNo()
			remark.setValue("申请地址：" +feeOrder.getRoomNo() + "，感谢您的关注与使用，订单详情，请点击查看。");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}



	@Override
	public int sendWxMsgByWarmHeart(WxUser user, ProductOrderWarmHeart orderWarmHeart) {
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<UserMp> qw = new QueryWrapper<>();
			qw.eq("union_id",user.getUnionId());
			qw.last("limit 1");
			UserMp userMp = userMpMapper.selectOne(qw);
			if(userMp != null){
				WxMsgTemplate template = getWarmHeartTemplateToUser(userMp,orderWarmHeart,23);
				String param = JSONUtil.parseObj(template).toString();
				System.out.println("公众号推送消息 - 用户端请求信息:" + param);
				JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
				System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());
				return 1;
			}
			return 0;
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  发送推送消息到 商家管理员微信上
	 * @param userMp
	 * @param orderWarmHeart
	 * @param template_type   10  物业费用通知
	 * @return
	 */
	private WxMsgTemplate getWarmHeartTemplateToUser(UserMp userMp, ProductOrderWarmHeart orderWarmHeart, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniProgram = new HashMap<>();
			miniProgram.put("appid",appid);
			miniProgram.put("pagepath","pages/order/detail/index?order_id=" + orderWarmHeart.getOrderId());
			template.setMiniprogram(miniProgram);

			Map<String, MsgTempData> m = new HashMap<>();
//			{{first.DATA}}
//			缴费项目：{{keyword1.DATA}}
//			缴费金额：{{keyword2.DATA}}
//			缴费日期：{{keyword3.DATA}}
//			{{remark.DATA}}
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的用户您好，您的暖心保订单已经支付完成。");
			m.put("first",first);

			//缴费项目
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue("日照暖心保");
			m.put("keyword1",keyword1);

			//缴费金额
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue("109元");
			m.put("keyword2",keyword2);

			//缴费日期
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(DateUtils.getDate());
			m.put("keyword3",keyword3);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			remark.setValue("详情请点击查看。如有相关保险问题，请致电暖心保客服：400-677-0633");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


	/**
	 *  提现申请成功 公众号推送消息
	 * @param user
	 * @param cashRecord
	 * @return
	 */
	@Override
	public int sendWxMsgTiXian(WxUser user, WxUserCashRecord cashRecord, double leftMoney){
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("dept_id",106);
			qw.eq("state",1);
			List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
			if(CollUtil.isNotEmpty(list)){
				for (SysUserWxAdmin wxAdmin : list){
					WxUser userAdmin = wxUserMapper.selectById(wxAdmin.getWxUserId());
					if(userAdmin != null){
						//充电开始通知
						WxMsgTemplate template = getTemplateToUser(userAdmin,cashRecord,15,leftMoney,1);
						String param = JSONUtil.parseObj(template).toString();
						JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
						System.out.println("公众号推送消息 - 财务人员信息:" + jsonObject.toString());
					}
				}
			}

			//充电开始通知
			WxMsgTemplate template = getTemplateToUser(user,cashRecord,15,leftMoney,0);
			String param = JSONUtil.parseObj(template).toString();
			JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
			System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());

		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  提现申请成功  商家管理员微信上
	 * @param user
	 * @param cashRecord
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getTemplateToUser(WxUser user, WxUserCashRecord cashRecord, Integer template_type,double leftMoney,int isAdmin){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		UserMp userMp = userMpMapper.selectOneByColumn("union_id",user.getUnionId());
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesMer/pages/account/index");
			template.setMiniprogram(miniprogram);

			Map<String, MsgTempData> m = new HashMap<>();
//			您好，您已提现成功！
//			提现金额：200元
//			提现时间：2018年4月10日 12：00
//			账户余额：400元
//			感谢您的使用。
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0){
				first.setValue("尊敬的用户您好，提现审核已通过");
			}else{
				first.setValue(cashRecord.getAccountName() +  "的提现审核已通过，款已打");
			}
			m.put("first",first);

			//提现金额
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(cashRecord.getPayMoney().doubleValue() + "元");
			m.put("keyword1",keyword1);

			//提现时间
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(DateUtils.getTime(cashRecord.getPayTime()));
			m.put("keyword2",keyword2);

			//账户余额
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(leftMoney + "元");
			m.put("keyword3",keyword3);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0) {
				remark.setValue("感谢您的使用。");
			}else{
				remark.setValue("操作员：" + cashRecord.getCheckSysUserName());
			}
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


	@Override
	public int sendWxMsgEggSettleSubmit(MerEggSettlement eggSettlement, double leftMoney) {
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("dept_id",106);
			qw.eq("state",1);
			List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
			if(CollUtil.isNotEmpty(list)){
				for (SysUserWxAdmin wxAdmin : list){
					WxUser userAdmin = wxUserMapper.selectById(wxAdmin.getWxUserId());
					if(userAdmin != null){
						//充电开始通知
						WxMsgTemplate template = getTemplateEggSettleToUser(userAdmin,eggSettlement,15,leftMoney,1);
						String param = JSONUtil.parseObj(template).toString();
						JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
						System.out.println("公众号推送消息 - 财务人员信息:" + jsonObject.toString());
					}
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}


	@Override
	public int sendWxMsgPromoterSettleSubmit(PromoterSettlement promoterSettlement, double leftMoney) {
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("dept_id",106);
			qw.eq("state",1);
			List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
			if(CollUtil.isNotEmpty(list)){
				for (SysUserWxAdmin wxAdmin : list){
					WxUser userAdmin = wxUserMapper.selectById(wxAdmin.getWxUserId());
					if(userAdmin != null){
						//充电开始通知
						WxMsgTemplate template = getTemplatePromoterSettleToUser(userAdmin,promoterSettlement,15,leftMoney,1);
						String param = JSONUtil.parseObj(template).toString();
						JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
						System.out.println("公众号推送消息 - 财务人员信息:" + jsonObject.toString());
					}
				}
			}

		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}



	@Override
	public int sendWxMsgEggSettle(WxUser user, MerEggSettlement eggSettlement, double leftMoney) {
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("dept_id",106);
			qw.eq("state",1);
			List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
			if(CollUtil.isNotEmpty(list)){
				for (SysUserWxAdmin wxAdmin : list){
					WxUser userAdmin = wxUserMapper.selectById(wxAdmin.getWxUserId());
					if(userAdmin != null){
						//充电开始通知
						WxMsgTemplate template = getTemplateEggSettleToUser(userAdmin,eggSettlement,15,leftMoney,2);
						String param = JSONUtil.parseObj(template).toString();
						JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
						System.out.println("公众号推送消息 - 财务人员信息:" + jsonObject.toString());
					}
				}
			}

			//充电开始通知
			WxMsgTemplate template = getTemplateEggSettleToUser(user,eggSettlement,15,leftMoney,0);
			String param = JSONUtil.parseObj(template).toString();
			JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
			System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());

		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}


	/**
	 *  提现申请成功  商家管理员微信上
	 * @param user
	 * @param eggSettlement
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getTemplateEggSettleToUser(WxUser user, MerEggSettlement eggSettlement, Integer template_type,double leftMoney,int isAdmin){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		UserMp userMp = userMpMapper.selectOneByColumn("union_id",user.getUnionId());
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesMer/pages/account/index");
			template.setMiniprogram(miniprogram);

			Map<String, MsgTempData> m = new HashMap<>();
//			您好，您已提现成功！
//			提现金额：200元
//			提现时间：2018年4月10日 12：00
//			账户余额：400元
//			感谢您的使用。
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0){
				first.setValue("尊敬的用户您好，领蛋结算审核已通过");
			}else if(isAdmin == 1){
				first.setValue(eggSettlement.getMerName() +  "的领蛋结算提现审核已通过，请尽快处理。");
			}else {
				first.setValue(eggSettlement.getMerName() +  "的领蛋结算提现审核已通过，款已打，请知悉。");
			}
			m.put("first",first);

			//提现金额
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(eggSettlement.getPayMoney().doubleValue() + "元");
			m.put("keyword1",keyword1);

			//提现时间
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(DateUtils.getTime(eggSettlement.getCreateTime()));
			m.put("keyword2",keyword2);

			//账户余额
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(leftMoney + "元");
			m.put("keyword3",keyword3);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0) {
				remark.setValue("感谢您的使用。");
			}else{
				remark.setValue("操作员：" + eggSettlement.getCheckSysUserName());
			}
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


	@Override
	public int sendWxMsgPromoterSettle(WxUser user, PromoterSettlement promoterSettlement, double leftMoney) {
		try{
			String access_token = getAccessToken(0);
			QueryWrapper<SysUserWxAdmin> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("dept_id",106);
			qw.eq("state",1);
			List<SysUserWxAdmin> list = sysUserWxAdminMapper.selectList(qw);
			if(CollUtil.isNotEmpty(list)){
				for (SysUserWxAdmin wxAdmin : list){
					WxUser userAdmin = wxUserMapper.selectById(wxAdmin.getWxUserId());
					if(userAdmin != null){
						//充电开始通知
						WxMsgTemplate template = getTemplatePromoterSettleToUser(userAdmin,promoterSettlement,15,leftMoney,2);
						String param = JSONUtil.parseObj(template).toString();
						JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
						System.out.println("公众号推送消息 - 财务人员信息:" + jsonObject.toString());
					}
				}
			}

			//充电开始通知
			WxMsgTemplate template = getTemplatePromoterSettleToUser(user,promoterSettlement,15,leftMoney,0);
			String param = JSONUtil.parseObj(template).toString();
			JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
			System.out.println("公众号推送消息 - 用户端响应信息:" + jsonObject.toString());

		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}


	/**
	 *  提现申请成功  商家管理员微信上
	 * @param user
	 * @param promoterSettlement
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getTemplatePromoterSettleToUser(WxUser user, PromoterSettlement promoterSettlement, Integer template_type,double leftMoney,int isAdmin){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		UserMp userMp = userMpMapper.selectOneByColumn("union_id",user.getUnionId());
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesMer/pages/account/index");
			template.setMiniprogram(miniprogram);

			Map<String, MsgTempData> m = new HashMap<>();
//			您好，您已提现成功！
//			提现金额：200元
//			提现时间：2018年4月10日 12：00
//			账户余额：400元
//			感谢您的使用。
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0) {
				first.setValue("尊敬的用户您好，推广结算审核已通过");
			}else if(isAdmin == 1){
				first.setValue("尊敬的管理员您好，推广结算审核已通过");
			}else{
//				first.setValue("尊敬的用户您好，"+ promoterSettlement.getPromoterName() + " 推广结算审核已通过");
				String name = "";
				if(StrUtil.isNotEmpty(promoterSettlement.getPromoterName())){
					name = EmojiParser.parseToUnicode(promoterSettlement.getPromoterName());
				}else{
					Promoter promoter = promoterMapper.selectById(promoterSettlement.getPromoterId());
					if(promoter!=null){
						if(StrUtil.isNotEmpty(promoter.getName())){
							name = EmojiParser.parseToUnicode(promoter.getName());
						}

						if(StrUtil.isEmpty(name)){
							name = promoter.getPhoneNum();
						}
					}
					if(StrUtil.isEmpty(name)) {
						WxUser wxUser = wxUserMapper.selectById(promoterSettlement.getPromoterWxUserId());
						if (wxUser != null) {
							if (StrUtil.isNotEmpty(wxUser.getNickName())) {
								name = EmojiParser.parseToUnicode(wxUser.getNickName());
							}
						}
					}
				}
				first.setValue(name +  " 推广结算提现审核已通过，款已打，请知悉。");
			}
			m.put("first",first);

			//提现金额
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(promoterSettlement.getPayMoney().doubleValue() + "元");
			m.put("keyword1",keyword1);

			//提现时间
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(DateUtils.getTime(promoterSettlement.getCreateTime()));
			m.put("keyword2",keyword2);

			//账户余额
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(leftMoney + "元");
			m.put("keyword3",keyword3);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			if(isAdmin == 0) {
				remark.setValue("共结算 " +promoterSettlement.getUserCount()+ "人，感谢您的支持，继续加油哦~。");
			}else{
				remark.setValue("结算人数：" + promoterSettlement.getUserCount() + "人 操作员：" + promoterSettlement.getCheckSysUserName());
			}
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


	/**
	 *  报修指派成功 公众号推送消息
	 * @param repairRecord
	 * @param template_type
	 * @return
	 */
	@Override
	public int sendWxMsgRepair(RepairRecord repairRecord, Integer template_type){
		try{
//			String access_token = redisTemplate.opsForValue().get("access_token_mp")!=null ? redisTemplate.opsForValue().get("access_token_mp").toString() : null;
//			if(StrUtil.isEmpty(access_token)){
//				access_token = WxMessage.getACCESSTOKEN(appidMp,secretMp);
//				redisTemplate.opsForValue().set("access_token_mp",access_token,3600L, TimeUnit.SECONDS);
//			}
			String access_token = getAccessToken(0);//WxMessage.getACCESSTOKEN(appidMp,secretMp);

			QueryWrapper<EstateUser> qw = new QueryWrapper<>();
			//财务部门
			qw.eq("estate_id",repairRecord.getEstateId());
			qw.eq("state",1);
			List<EstateUser> list = estateUserService.list(qw);
			if(CollUtil.isNotEmpty(list)){
				for (EstateUser estateUser : list){
					WxUser user1 = wxUserMapper.selectById(estateUser.getUserId());
					if(user1!=null){
						UserMp userMp = userMpMapper.selectOneByColumn("union_id",user1.getUnionId());
						if(userMp!=null){
							WxMsgTemplate template = getRepairTemplateToManager(userMp,repairRecord,17);
							String param = JSONUtil.parseObj(template).toString();
							JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
							System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
						}
					}
				}
			}

			QueryWrapper<Worker> qwWorker = new QueryWrapper<>();
			//财务部门
			qwWorker.eq("estate_id",repairRecord.getEstateId());
			qwWorker.eq("state",0);
			List<Worker> workers = workerService.list(qwWorker);
			if(CollUtil.isNotEmpty(workers)){
				for (Worker worker : workers){
					WxUser user1 = wxUserMapper.selectById(worker.getWxUserId());
					if(user1!=null){
						UserMp userMp = userMpMapper.selectOneByColumn("union_id",user1.getUnionId());
						if(userMp!=null){
							WxMsgTemplate template = getRepairTemplateToManager(userMp,repairRecord,17);
							String param = JSONUtil.parseObj(template).toString();
							JSONObject jsonObject = WxMessage.sendMsg(access_token,param);
							System.out.println("公众号推送消息 - 新报修记录:" + jsonObject.toString());
						}
					}
				}
			}
		}catch (Exception e){
			e.printStackTrace();
			System.out.println("发送失败" + e.getMessage());
		}
		return 1;
	}

	/**
	 *  发送推送消息到 管理员微信上
	 * @param userMp
	 * @param repairRecord
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getRepairTemplateToManager(UserMp userMp, RepairRecord repairRecord, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		if(wxTemplate!=null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesProperty/pages/repairInfo/index?id=" +repairRecord.getId());
			template.setMiniprogram(miniprogram);

			Map<String, MsgTempData> m = new HashMap<String, MsgTempData>();
//			{{first.DATA}}
//			工单编号：{{keyword1.DATA}}
//			报修位置：{{keyword2.DATA}}
//			报修内容：{{keyword3.DATA}}
//			维修服务人员：{{keyword4.DATA}}
//			报修类型：{{keyword5.DATA}}
//			{{remark.DATA}}
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的小区管理员，报修任务已派发，请悉知并关注跟进");
			m.put("first",first);

			//工单编号
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(repairRecord.getRecordNo());
			m.put("keyword1",keyword1);

			//报修位置
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(repairRecord.getEstateName() +  repairRecord.getRoomNo());
			m.put("keyword2",keyword2);

			//报修内容
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(repairRecord.getContent());
			m.put("keyword3",keyword3);

			//维修服务人员
			MsgTempData keyword4 = new MsgTempData();
			keyword4.setColor(wxTemplate.getFontColor());
			keyword4.setValue(repairRecord.getOpUserName());
			m.put("keyword4",keyword4);

			//报修类型
			MsgTempData keyword5 = new MsgTempData();
			keyword5.setColor(wxTemplate.getFontColor());
			if(repairRecord.getCheckType() == 0){
				keyword5.setValue("屋外报修");
			}else{
				keyword5.setValue("屋内报修");
			}
			m.put("keyword5",keyword5);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			remark.setValue("该工单已安排"+repairRecord.getOpUserName() + "进行处理，请及时跟进。感谢您对本工作的支持与付出。");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


	@Override
	public int sendWxMsgElectricRecharge(ElectricOrder order, int isOver) {
		WxUser user = wxUserMapper.selectById(order.getUserId());
		try {
			String access_token = getAccessToken(0);
			//充电结束通知
			WxMsgTemplate template = getElectricRechargeToUser(user,order,21,isOver);
			String param = JSONUtil.parseObj(template).toString();
			JSONObject jsonReturn = WxMessage.sendMsg(access_token,param);
			System.out.println("公众号推送消息 - 用户端响应信息:" + jsonReturn.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}


	/**
	 *  结束充电 发给用户的推送消息
	 * @param user
	 * @param order
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getElectricRechargeToUser(WxUser user, ElectricOrder order, Integer template_type,int isOver){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		UserMp userMp = userMpMapper.selectOneByColumn("union_id",user.getUnionId());
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesDevice/pages/charger/orderList/index");
			template.setMiniprogram(miniprogram);

//            ElectricMeter meter = chargerService.findById(chargerOrder.getDeviceId());
			Map<String, MsgTempData> m = new HashMap<>();

//            {{first.DATA}}
//            电表名称：{{keyword1.DATA}}
//            充值金额：{{keyword2.DATA}}
//            充值时间：{{keyword3.DATA}}
//            {{remark.DATA}}

			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			if(isOver == 0){
				first.setValue("您好，当前电表已经充值成功。电费到账导致可能存在延迟，请耐心等待。");
			} else {
				first.setValue("您好，当前电表已经充值成功。电费到账" +order.getTotalPrice()+"元，请注意查收。");
			}
			m.put("first",first);

			//电表名称
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(order.getDeviceName() + "("+order.getDeviceSn()+")");
			m.put("keyword1",keyword1);

			//充值金额
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(DateUtils.getTime(new Date()));
			m.put("keyword2",keyword2);

			//充值时间
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			keyword3.setValue(DateUtils.getTime(order.getPayTime()));
			m.put("keyword3",keyword3);

			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			remark.setValue("如有疑问，可联系物业管理处进行反馈。谢谢！ ");
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}



	/**
	 * 发送充电开始公众号推送消息
	 * @param chargerOrder
	 * @return
	 */
	@Override
	public int sendWxMsgEndCharger(ChargerOrder chargerOrder) {
		WxUser user = wxUserMapper.selectById(chargerOrder.getUserId());
		JSONObject jsonObject = new JSONObject();
		jsonObject.set("order_id",chargerOrder.getId());
		jsonObject.set("user_id",user.getId());
		jsonObject.set("order","10");
		try {
			String access_token = getAccessToken(0);
			//充电结束通知
			WxMsgTemplate template = getEndChargerTemplateToUser(user,chargerOrder,13);
			String param = JSONUtil.parseObj(template).toString();
			JSONObject jsonReturn = WxMessage.sendMsg(access_token,param);
			System.out.println("公众号推送消息 - 用户端响应信息:" + jsonReturn.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 1;
	}


	/**
	 *  结束充电 发给用户的推送消息
	 * @param user
	 * @param chargerOrder
	 * @param template_type
	 * @return
	 */
	private WxMsgTemplate getEndChargerTemplateToUser(WxUser user, ChargerOrder chargerOrder, Integer template_type){
		WxMsgTemplate template = new WxMsgTemplate();
		WxTemplate wxTemplate = wxTemplateMapper.selectOneByColumn("template_type",template_type);
		UserMp userMp = userMpMapper.selectOneByColumn("union_id",user.getUnionId());
		if(userMp != null){
			template.setTouser(userMp.getOpenId());
			template.setTemplate_id(wxTemplate.getTemplateId());
			template.setUrl("");

			Map<String,Object> miniprogram = new HashMap<>();
			miniprogram.put("appid",appid);
			miniprogram.put("pagepath","pagesDevice/pages/charger/orderList/index");
			template.setMiniprogram(miniprogram);

			Charger charger = chargerService.findById(chargerOrder.getDeviceId());
			Map<String, MsgTempData> m = new HashMap<>();
//            {{first.DATA}}
//            充电地址：{{keyword1.DATA}}
//            结束时间：{{keyword2.DATA}}
//            消费金额：{{keyword3.DATA}}
//            退还金额：{{keyword4.DATA}}
//            账户余额：{{keyword5.DATA}}
//            {{remark.DATA}}
			MsgTempData first = new MsgTempData();
			first.setColor(wxTemplate.getFontColor());
			first.setValue("尊敬的用户您好，充电已结束。");
			m.put("first",first);

			//充电地址
			MsgTempData keyword1 = new MsgTempData();
			keyword1.setColor(wxTemplate.getFontColor());
			keyword1.setValue(charger.getAddress());
			m.put("keyword1",keyword1);

			//结束时间
			MsgTempData keyword2 = new MsgTempData();
			keyword2.setColor(wxTemplate.getFontColor());
			keyword2.setValue(DateUtils.getTime(new Date()));
			m.put("keyword2",keyword2);

			//消费金额
			MsgTempData keyword3 = new MsgTempData();
			keyword3.setColor(wxTemplate.getFontColor());
			if(chargerOrder.getIsFree() == 0){
				keyword3.setValue(chargerOrder.getUsePrice().doubleValue() + "元");
			}else{
				keyword3.setValue("0.00元");
			}
			m.put("keyword3",keyword3);

			double leftMoney = MathUtil.getDoubleUp(chargerOrder.getTotalPrice().doubleValue() - chargerOrder.getUsePrice().doubleValue());
			//退还金额
			MsgTempData keyword4 = new MsgTempData();
			keyword4.setColor(wxTemplate.getFontColor());

			if(chargerOrder.getIsFree() == 0) {
				keyword4.setValue(leftMoney + "元");
			}else{
				keyword4.setValue("0.00元");
			}
			m.put("keyword4",keyword4);


			//账户余额
			MsgTempData keyword5 = new MsgTempData();
			keyword5.setColor(wxTemplate.getFontColor());
			keyword5.setValue("0.00元");
			m.put("keyword5",keyword5);


			MsgTempData remark = new MsgTempData();
			remark.setColor(wxTemplate.getFontColor());
			if(chargerOrder.getIsFree() == 0){
				if(leftMoney > 0){
					remark.setValue("尊敬的业主，您的爱车充电已结束，由于电动车功率大小不同，充电时长以最终设备检测实际显示为准，剩余的余额已退回到您的微信账户，感谢您的使用。");
				}else{
					remark.setValue("尊敬的业主，您的爱车充电已结束，由于电动车功率大小不同，充电时长以最终设备检测实际显示为准，感谢您的使用。");
				}
			}else{
				remark.setValue("尊敬的业主，您的爱车充电已结束，感谢您的免费使用。");
			}
			m.put("remark",remark);

			template.setData(m);
		}
		return template;
	}


}
